﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Threading;

using NTwitter;
using System.Threading;
using TransitionEffects;
using System.Windows.Media.Animation;
using System.Windows.Controls.Primitives;
using Deepforest.TweetMe.UI.Properties;

namespace Deepforest.TweetMe.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {        
        private Twitter Twitter { get; set; }
        private KeyboardHook Hook { get; set; }
        System.Windows.Forms.NotifyIcon NotifyIcon { get; set; }

        public MainWindow()
        {
            NotifyIcon = new System.Windows.Forms.NotifyIcon();
            var iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/Twitter.ico")).Stream;
            NotifyIcon.Icon = new System.Drawing.Icon(iconStream);
            NotifyIcon.Visible = true;            
            NotifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(
                new System.Windows.Forms.MenuItem[]
                {
                    new System.Windows.Forms.MenuItem("Open Tweet Me!", (s, e) => Show()),
                    new System.Windows.Forms.MenuItem("Settings", (s, e) => OpenSettings()),
                    new System.Windows.Forms.MenuItem(""),
                    new System.Windows.Forms.MenuItem("Exit", (s, e) => Close())
                }
            );
            NotifyIcon.MouseClick += NotifyIcon_MouseClick;
            
            Twitter = new Twitter(Settings.Default.UserName, Settings.Default.Password);

            InitializeKeyboardHook();
            InitializeComponent();

            TextBoxTweet.Focus();
        }

        void NotifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //if (e.Button == System.Windows.Forms.MouseButtons.Right)
            //{
            //    var contextMenu = new ContextMenu();
            //    contextMenu.Items.Add("Test...");
            //    contextMenu.Width = 120;
            //    contextMenu.Height = 200;
            //    contextMenu.Placement = PlacementMode.Mouse;
            //    contextMenu.StaysOpen = false;
            //    contextMenu.IsOpen = true;
            //    //var popup = new Popup()
            //    //{
            //    //    Width = 120,
            //    //    Height = 200,
            //    //    Child = new Button() { Content = "test" },
            //    //    Placement = PlacementMode.Mouse,
            //    //    PlacementRectangle = new Rect(0, 0, 120, 200)
            //    //};
            //    //popup.IsOpen = true;                
            //    //popup.StaysOpen = false;
                

            //}
            
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (Visibility == Visibility.Visible)
                {
                    HideWithEffect();
                }
                else
                {
                    Show();
                }
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            NotifyIcon.Visible = false;
            NotifyIcon.Dispose();
            Hook.Dispose();

            base.OnClosing(e);
        }

        private void InitializeKeyboardHook()
        {
            Hook = new KeyboardHook();
            Hook.KeyDown += new KeyboardHook.HookEventHandler(Hook_KeyDown);
        }

        void Hook_KeyDown(object sender, HookEventArgs e)
        {
            if (e.Control && e.Key == System.Windows.Forms.Keys.Q && Visibility == Visibility.Hidden)
            {
                Show();                
            }
        }

        private bool firstHide = true;
        private bool hinding = false;

        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape && !hinding)
            {
                HideWithEffect();
                
                e.Handled = true;                
            }
            else if (e.Key == Key.Enter)
            {
                if (!string.IsNullOrEmpty(TextBoxTweet.Text))
                {
                    SendTweet(TextBoxTweet.Text);
                }

                HideWithEffect();

                e.Handled = true;                
            }
            else
            {
                TextBoxTweet.Focus();
            }

            base.OnKeyDown(e);
        }        

        private void HideWithEffect()
        {            
            hinding = true;

            TextBoxTweet.Clear();

            var effect = new RadialBlurTransitionEffect();            

            var opacityAnim = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromSeconds(1.0)), FillBehavior.Stop);            
            opacityAnim.AccelerationRatio = 0.5;
            opacityAnim.DecelerationRatio = 0.5;

            var effectAnim = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(1.0)), FillBehavior.HoldEnd);
            effectAnim.AccelerationRatio = 0.5;
            effectAnim.DecelerationRatio = 0.5;
            effectAnim.Completed += hideStoryboard_Completed;

            Effect = effect;

            BeginAnimation(FrameworkElement.OpacityProperty, opacityAnim);
            effect.BeginAnimation(TransitionEffect.ProgressProperty, effectAnim);
        }

        void hideStoryboard_Completed(object sender, EventArgs e)
        {
            if (firstHide)
            {
                NotifyIcon.ShowBalloonTip(
                    10000,
                    "Tweet Me! is still running",
                    "Tweet Me! is running in the background. You may right click on the tray icon and select 'Exit' to close it at any time.",
                    System.Windows.Forms.ToolTipIcon.Info);

                firstHide = false;
            }

            Effect = null;

            Hide();

            hinding = false;
        }

        private void TextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            OpenSettings();
        }

        private void OpenSettings()
        {
            var settingsDialog = new SettingsDialog();
            if (settingsDialog.ShowDialog() == true)
            {
                Twitter = new Twitter(Settings.Default.UserName, Settings.Default.Password);
            }
        }

        private void SendTweet(string tweet)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    //if (MessageBox.Show("Send tweet?", "Tweet Me!", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    //{
                    Twitter.UpdateStatus(tweet);
                    //}
                }
                catch (Exception ex)
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
                    {
                        NotifyIcon.ShowBalloonTip(
                            10000,
                            "Send tweet error",
                            "Tweet Me! has encountered an error while trying to send a tweet. Please make sure that the user name and password you've provided are correct.",
                            System.Windows.Forms.ToolTipIcon.Error);                        
                    });
                }
            });
        }
    }
}
